<?php

namespace App\Http\Controllers\Admin;

use App\Enums\SmsTempEnum;
use App\Exceptions\ApiErrorException;
use App\Jobs\SendChangeOrderMessage;
use App\Jobs\SendSmsMessageJob;
use App\Models\AppTypeModel;
use App\Models\Areas;
use App\Models\AuthenticLog;
use App\Models\BillReport;
use App\Models\Express;
use App\Models\MemberAlipayRisk;
use App\Models\MemberDlzwRisk;
use App\Models\MemberLegal;
use App\Models\MemberOther;
use App\Models\MemberQnRisk;
use App\Models\NewAdmin;
use App\Models\Order;
use App\Models\OrderDepict;
use App\Models\OrderDlzwRisk;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use App\Models\OrderLeasePartial;
use App\Models\OrderLog;
use App\Models\OrderRadarXinyan;
use App\Models\OrderRate;
use App\Models\OrderRefund;
use App\Models\OrderRemark;
use App\Models\OrderReturn;
use App\Models\OrderRiskAlipay;
use App\Models\OrderRiskBoolea;
use App\Models\OtherWithholdLog;
use App\Models\ShopSms;
use App\Models\ShopTrans;
use App\Models\TransDetail;
use App\Models\OrderRadarBoolea;
use App\Models\OrderEduBoolea;
use App\Models\ShopUser;
use App\Models\OrderCredit;
use App\Models\TwoElements;
use App\Services\AlipayMiniOrderService;
use App\Services\AlipayRiskService;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\CommonService;
use App\Services\CreditCallService;
use App\Services\EducationService;
use App\Services\EsignService;
use App\Services\ExportService;
use App\Services\GoodsService;
use App\Services\InteractiveRiskQueryService;
use App\Services\LogisticsService;
use App\Services\RedisLock;
use App\Services\RedisService;
use App\Services\RelationVerifyService;
use App\Services\RiskDlzwService;
use App\Services\RiskService;
use App\Services\RadarService;
use App\Services\OrderService;
use App\Services\CreditService;
use App\Services\WechatService;
use App\Services\XinyanService;
use Illuminate\Http\Request;
use App\Services\AlipayMessageService;
use App\Services\AntchainPlusService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class OrderController extends BaseController
{
    /**
     * 订单列表
     * @param Request $request
     * @return false|string
     */
    public function orderList(Request $request)
    {

        $request['role_id']=$this->users['role_id'];

        $data = Order::orderList($request);
        $count = Order::computeStatus($request);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ['count' => $count, 'list' => $data['list']]);
    }

    /**
     * 教育信息
     * @param Request $request
     * @return false|string
     */
    public function getEducation(Request $request)
    {
        $order = Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->select(
                'o.id', 'o.uid', 'o.mobile as user_mobile', 'o.trade_no'
                , 'm.cert_name', 'm.cert_no'
                , 'm.education'
            )
            ->first();

        if (!$order) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或者状态不是待付款');
        }

        if (empty($order['education'])) {
            $res = EducationService::query($order);
            if ($res['retcode'] == '000000' || $res['retcode'] == '') {
                $umem = MemberOther::where('id', $order['uid'])->update(['education' => isset($res['data']) ? json_encode($res['data']) : '无学历信息']);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, $umem ? '获取成功' : '获取失败');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['retmsg']);
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', json_decode($order['education'], true));
        }
    }


    /**
     * 通话时长
     * @param Request $request
     * @return false|string
     */
    public function getMobile3m(Request $request)
    {
        $order = Order::from('sp_order_2 as o')->where('o.id', $request['orderId'])
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->select(
                'o.id', 'o.uid', 'o.mobile as user_mobile', 'o.trade_no'
                , 'm.cert_name', 'm.cert_no'
                , 'm.minutes', 'm.mobile'
            )
            ->first();

        if (!$order) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }

        if (empty($order['minutes'])) {
            $RelationVerifyService = new RelationVerifyService();
            $res = $RelationVerifyService->mobile3mQuery($order);
            if ($res['code'] && $res['code'] == '200') {
                MemberOther::where('id', $order['uid'])->update(['minutes' => isset($res['data']['minutes']) ? $res['data']['minutes'] : $res['data']['messge']]);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['retmsg']);
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', json_decode($order['education'], true));
        }
    }

    /**
     * 支付宝履约等级
     * @param Request $request
     * @return false|string
     */
    public function alipayPerformanceRead(Request $request)
    {
        $order = Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->select(
                'o.id', 'o.uid', 'm.mobile', 'o.trade_no'
                , 'm.cert_name', 'm.cert_no', 'm.user_id'
                , 'm.education', 'o.status', 'm.level_performance'
            )
            ->first();


        if (!empty($order['level_performance'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已查询');
        }

        $data = AlipayRiskService::levelPerformance($order['cert_no'], $order['uid'], 0);

        if ($data == '未知') {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '查询失败');
        }

        //添加备注
        $add = [
            'uid' => $this->users['id'],
            'username' => $this->users['username'],
            'create_time' => time(),
            'remark' => $this->users['username'] . '查看支付宝履约等级',
            'order_id' => $request['order_id']
        ];
        OrderRemark::insert($add);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功');
    }

    /**
     * 支付宝风险识别
     * @param Request $request
     * @return false|string
     */
    public function alipayRead(Request $request)
    {
        $order = Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->select(
                'o.id', 'o.uid', 'm.mobile', 'o.trade_no'
                , 'm.cert_name', 'm.cert_no', 'm.user_id'
                , 'm.education', 'o.status', 'm.level'
            )
            ->first();

        if (empty($order['user_id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '非支付宝用户');
        }

        if (!empty($order['level'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已查询');
        }

        $data = InteractiveRiskQueryService::alipayRead($order['user_id'], 0, $order);

        if ($data == '未知') {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '查询失败');
        }


        //添加备注
        $add = [
            'uid' => $this->users['id'],
            'username' => $this->users['username'],
            'create_time' => time(),
            'remark' => $this->users['username'] . '查看支付宝风险评估等级',
            'order_id' => $request['order_id']
        ];
        OrderRemark::insert($add);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功');
    }

    /**
     * 小程序云智能租赁风控查询
     * @param Request $request
     * @return false|string
     */
    public function rentRiskQuery(Request $request)
    {
        // $order = Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])
        //     ->select(
        //         'o.id', 'o.uid', 'o.trade_no'
        //     )
        //     ->first();
//        $one=MemberAlipayRisk::query($order['uid']);
//        if(!empty($one)){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'已查询');
//        }
        $order = Order::from('sp_order_2 as o')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
            ->where('o.id', $request['order_id'])
            ->select('m.mobile', 'm.cert_name', 's.mechanism', 'm.cert_no', 'o.mini_id', 'o.trade_no', 'o.realname', 'o.address',
                'o.month_total', 'o.address', 'o.address', 'o.id', 's.member_id', 'o.uid', 'o.seller_id', 'og.goods_title', 'og.imgurl', 'm.gender', 'og.setmeal_title')
            ->first()->toArray();
        if (empty($order['cert_no'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '用户身份证未上传');
        }
        $miniId = $order['mini_id'];

        $order['rent'] = OrderLease::where('order_id', $order['id'])->where('which_period', '1')->value('rent');
        $res = AlipayService::rentriskQuery($miniId, $order);

        if (!$res['status']) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '查询失败');
        }
        $res = $res['data'];
        MemberAlipayRisk::insertMember($order['cert_no'], $order['cert_name'], $order['mobile'], $order['uid'], $res['risk_name'], $res['risk_desc'], json_encode($res, JSON_UNESCAPED_UNICODE));
        //添加备注
        $add = [
            'uid' => $this->users['id'],
            'username' => $this->users['username'],
            'create_time' => time(),
            'remark' => $this->users['username'] . '查询智租风控',
            'order_id' => $request['order_id']
        ];
        OrderRemark::insert($add);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功');
    }

    /**
     * 申请退押金或碎屏险
     * @param Request $request
     * @return false|string
     */
    public function applyRefundDeposit(Request $request){
        try{
            $orderId = $request->input('orderId','');
            $refund_deposit_status = $request->input('refund_deposit_status','0');
            $refund_screen_status = $request->input('refund_screen_status','0');

            if(!$orderId){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            if(!Order::checkOrderById($orderId)){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未找到订单信息');
            }
            if(empty($refund_deposit_status)&&empty($refund_screen_status)){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请选择要申请退押金或碎屏险');
            }
            $OrderDepict=OrderDepict::query()->where(['order_id'=>$orderId])->first();
            if(!$OrderDepict){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未找到押金信息');
            }
            if(($OrderDepict['refund_deposit_status']==1||$OrderDepict['refund_deposit_status']==2)&&$refund_deposit_status){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该订单已申请过退押金');
            }else if($refund_deposit_status){
                $res= OrderDepict::query()->where(['order_id'=>$orderId])->update(['refund_deposit_status'=>1]);
            }
            if(($OrderDepict['refund_screen_status']==1||$OrderDepict['refund_screen_status']==2)&&$refund_screen_status){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该订单已申请过退碎屏险');
            }else if($refund_screen_status){
                $res=OrderDepict::query()->where(['order_id'=>$orderId])->update(['refund_screen_status'=>1]);
            }
            if($res){
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'申请成功');
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'申请失败');
            }
        }catch (\Exception $exception){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'修改失败');
        }
    }

    /**
     * 风控查询
     * @param Request $request
     * @return false|string
     */
    public function accurateRiskQuery(Request $request)
    {

        $order = Order::from('sp_order_2 as o')->where('o.id',$request['order_id'])
            ->leftjoin('sp_member_2 as m','m.id','o.uid')
            ->select(
                'o.id','o.uid','o.mobile as user_mobile','o.pact_url_5','o.trade_no'
                ,'m.cert_name','m.cert_no','o.sale_user_id','o.prov'
                ,'m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
            )
            ->first();

        $one= OrderDlzwRisk::query()->where('order_id',$order['id'])->orderBy('id','desc')->exists();
        if($one){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'已查询,请等待结果返回');
        }


        if(empty($order['cert_no'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'用户身份证未上传');
        }
        $res=RiskDlzwService::shopInquire($order);

        if($res['code']!=200){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,$res['msg']);
        }
        //添加备注
        $add = [
            'uid'=>$this->users['id'],
            'username'=>$this->users['username'],
            'create_time'=>time(),
            'remark'=>$this->users['username'].'查询风控建议',
            'order_id'=>$request['order_id']
        ];
        OrderRemark::insert($add);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功');
    }


    /**
     * 芝麻风控
     * @param Request $request
     * @return false|string
     */
    public function rentRiskCreditQuery(Request $request)
    {
        $order = Order::from('sp_order_2 as o')
            ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
            ->where('o.id', $request['order_id'])
            ->select('m.mobile', 'm.cert_name', 's.mechanism', 'm.cert_no', 'o.mini_id', 'o.trade_no', 'o.realname', 'o.address',
                'o.month_total', 'o.address', 'o.address', 'o.id', 's.member_id', 'o.uid', 'o.alipay_trade_no', 'o.rights_auth_no', 'o.seller_id', 'og.goods_title', 'og.imgurl', 'm.gender', 'og.setmeal_title')
            ->first()->toArray();

        if (empty($order['alipay_trade_no']) || empty($order['rights_auth_no'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '用户未授权芝麻免押');
        }
        $res = AlipayService::alipayCreditPreQuery($order['mini_id'], $order);
        if (!$res['status']) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['message']);
        }
        //添加备注
        $add = [
            'uid' => $this->users['id'],
            'username' => $this->users['username'],
            'create_time' => time(),
            'remark' => $this->users['username'] . '查询芝麻风控',
            'order_id' => $request['order_id']
        ];
        OrderRemark::insert($add);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功');
    }

    /**
     * 修改订单状态
     * @param Request $request
     * @return false|string
     */
    public function updateOrderStatus(Request $request)
    {
        $order = Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->select(
                'o.id', 'o.uid', 'o.mobile as user_mobile', 'o.trade_no'
                , 'm.cert_name', 'm.cert_no'
                , 'm.education', 'o.status'
            )
            ->first();

        if ($order['status'] != 3) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或者状态不是待付款');
        }

        Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])->update(['status' => 4]);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
    }

    /**
     * 工作稳定性结果查询
     * @param Request $request
     * @return false|string
     */
    public function getStableWealthReport(Request $request)
    {
        $order = Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->select(
                'o.id', 'o.uid', 'o.mobile as user_mobile', 'o.trade_no'
                , 'm.cert_name', 'm.cert_no'
                , 'm.education'
            )
            ->first();

        if (!$order) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或者状态不是待付款');
        }

        if (empty($order['stable_wealth'])) {
            $res = EducationService::stableWealthReport($order);
            if (isset($res['err_code']) && $res['err_code'] == '200') {
                $umem = MemberOther::where('id', $order['uid'])->update(['stable_wealth' => isset($res['data']['stable_wealth_report']) ? json_encode($res['data']['stable_wealth_report'], JSON_UNESCAPED_UNICODE) : '无工作稳定性报告']);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, $res['retmsg']);
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['retmsg']);
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功');
        }
    }

    /**
     * 姓名与手机号二要素验证
     * @param Request $request
     * @return false|string
     */
    public function getAuthPhoneName(Request $request)
    {
        if (!isset($request['phone']) || empty($request['name'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数有误');
        }
        $order = Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->select(
                'o.id', 'o.uid', 'o.mobile as user_mobile', 'o.trade_no'
                , 'm.cert_name', 'm.cert_no'
                , 'm.education', 'm.mobile',
            )
            ->first();

        if (!$order) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }

        if (!Verify_Phone($request['phone'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '手机号码有误');
        }
        $res = TwoElements::where('order_id', $request['order_id'])
            ->where('phone', $request['phone'])
            ->value('id');
//        if($res){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '此手机号码已查询');
//        }

        $data = ['order_id' => $request['order_id'], 'relate' => $request['relate'], 'phone' => $request['phone'], 'name' => $request['name']];
        $res = EducationService::queryTwoName($request);
        $res = json_decode($res, true);
        if ($res['code'] == '0' && $res['data']['VerificationResult'] != '-1') {
            $data['result'] = $res['data']['ISP'];
//            var_dump($data['result']);
            if ($data['result'] == 'CM') {
                $RelationVerifyService = new RelationVerifyService;
                $relationRes = $RelationVerifyService->query(['mobile' => $order['mobile'], 'provider' => '1', 'targetNumber' => $request['phone']]);
                $data['result_code'] = $relationRes['data']['resultCode'];
                $data['vcode'] = $relationRes['data']['vcode'];
            }

            $res = TwoElements::insert($data);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, $res ? '获取成功' : '获取失败');

        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '查询失败，号码与姓名验证错误');
        }

//            $res=TwoElements::insertCheckPhone($request['order_id'],$request['phone'],$request['name']);
//            if($res){
//                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,$res?'获取成功':'获取失败');
//            }else{
//                return ReturnMsg(CommonService::HTTP_CODE_FAIL,$res['message']);
//            }

    }

    /**
     * 姓名与手机号二要素验证
     * @param Request $request
     * @return false|string
     */
    public function getOrderCheckPhonelist(Request $request)
    {
        $data = TwoElements::getOrderAll($request['order_id']);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 订单列表
     * @param Request $request
     * @return false|string
     */
    public function orderSuccessList(Request $request)
    {
        $data = Order::orderList($request);
        $count = Order::computeStatusSuccess($data['count']);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ['count' => $count, 'list' => $data['list']]);
    }

    /**
     * 征信订单列表
     * @param Request $request
     * @return false|string
     */
    public function creditOrderList(Request $request)
    {

        $data = Order::creditOrderList($request);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 划扣订单提前提醒列表(订单划扣日提前3天),可根据某个日期筛选
     * @param Request $request
     * @return false|string
     */
    public function orderRemindList(Request $request)
    {
        $data = Order::orderRemindList($request);
        // $count = Order::computeStatus($data['count']);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ['list' => $data['list']]);
    }

    /**
     * 新逾期订单
     * @param Request $request
     * @return false|string
     */
    public function orderOverdueList(Request $request)
    {
        $data = Order::orderOverdueList($request);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ['list' => $data['list']]);
    }

    /**
     * 花呗订单列表
     * @param Request $request
     * @return false|string
     */
    public function orderHuaBeiList(Request $request)
    {
        $where[] = ['o.pay_type', Order::ORDER_PAY_TYPE_HUABEI];
        $data = Order::orderList($request, $where);
        $count = [
            OrderService::ORDER_LIST_STATUS_ALL => 0, //全部订单
            OrderService::ORDER_LIST_STATUS_NOT_PAY => 0, //待付款订单
            OrderService::ORDER_LIST_STATUS_NOT_RISK => 0, //待风控订单
            OrderService::ORDER_LIST_STATUS_DELIVERED_NOT => 0, //待发货订单
            OrderService::ORDER_LIST_STATUS_DELIVERED_IS => 0, //已发货订单
            OrderService::ORDER_LIST_STATUS_ING => 0, //租用中订单
            OrderService::ORDER_LIST_STATUS_COMPLETED => 0, //交易完成订单
            OrderService::ORDER_LIST_STATUS_CANCEL => 0, //取消订单
            OrderService::ORDER_LIST_STATUS_REFUND => 0, //退款订单
        ];
        $count = Order::computeStatus($data['count'], $count);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ['count' => $count, 'list' => $data['list']]);
    }

    /**
     * 续租订单列表
     * @param Request $request
     * @return false|string
     */
    public function orderRenewalList(Request $request)
    {
        $where[] = ['o.is_renewal', Order::ORDER_IS_RENEWAL];
        $data = Order::orderList($request, $where);
        $count = [
            OrderService::ORDER_LIST_STATUS_ALL => 0, //全部订单
            OrderService::ORDER_LIST_STATUS_NOT_PAY => 0, //待付款订单
            OrderService::ORDER_LIST_STATUS_ING => 0, //租用中订单
            OrderService::ORDER_LIST_STATUS_RETURN => 0, //归还订单
            OrderService::ORDER_LIST_STATUS_COMPLETED => 0, //交易完成订单
            OrderService::ORDER_LIST_STATUS_BUY_OUT => 0, //买断订单
            OrderService::ORDER_LIST_STATUS_REFUND => 0, //退款订单
        ];
        $count = Order::computeStatus($data['count'], $count);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ['count' => $count, 'list' => $data['list']]);
    }

    /**
     * 买断订单列表
     * @param Request $request
     * @return false|string
     */
    public function orderBuyOutList(Request $request)
    {
        $where[] = ['o.status', OrderService::ORDER_STATUS_BUYOUT_PAY];
        $data = Order::orderList($request, $where);
        $count = [
            OrderService::ORDER_LIST_STATUS_ALL => 0, //全部订单
        ];
        $count = Order::computeStatus($data['count'], $count);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ['count' => $count, 'list' => $data['list']]);
    }

    /**
     * 签约待付款订单列表
     * @param Request $request
     * @return false|string
     */
    public function orderSignedList(Request $request)
    {
        $where[] = ['o.status', OrderService::ORDER_STATUS_SIGN_NOTPAY];
        $data = Order::orderList($request, $where);
        $count = [
            OrderService::ORDER_LIST_STATUS_ALL => 0, //全部订单
        ];
        $count = Order::computeStatus($data['count'], $count);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', ['count' => $count, 'list' => $data['list']]);
    }

    /**
     * 查看租期
     * @param Request $request
     * @return false|string
     */
    public function getLease(Request $request)
    {

        $orderId = $request->input('orderId', '');
        if (!$orderId) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!Order::checkOrderById($orderId)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
        }
        $where[] = ['o.id', $orderId];
        $where[] = ['o.status', '>', OrderService::ORDER_STATUS_NOT_PAY];
        $data = Order::from('sp_order_2 as o')
            ->select('o.trade_no', 'ol.order_id', 'o.pay_type', 'o.status as order_status', 'o.month_total', 'ol.id', 'ol.which_period', 'ol.rent', 'ol.paid_rent',
                'ol.begin_time', 'ol.end_time', 'ol.status', 'ol.pay_time', 'ol.alipay_trade_no', 'ol.out_order_no', 'ol.withhold_status', 'ol.result', 'ol.result_time',
                'ol.result1', 'ol.result_time1', 'ol.overdue_days', 'ol.overdue_amount')
            ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
            ->where($where)
            ->orderBy('ol.which_period', 'asc')
            ->get();
        $data = obToArray($data);
        foreach ($data as &$itme) {
            //代扣按钮 默认关闭
            $itme['is_withhold'] = OrderLease::LEASE_WITHHOLD_STATUS_OFF;
            if (OrderLease::withholdLimit($itme['order_status'], $itme['withhold_status'], $itme['begin_time'], $itme['status'], false)) {
                $itme['is_withhold'] = OrderLease::LEASE_WITHHOLD_STATUS_NO;
            }
            $itme['begin_time'] = dateDFormat($itme['begin_time']);
            $itme['end_time'] = dateDFormat($itme['end_time']);
            $itme['pay_time'] = dateFormat($itme['pay_time']);
            $last_rent = bcsub($itme['rent'], $itme['paid_rent'], 2);
            $itme['last_rent'] = $last_rent < 0 ? '0.00' : $last_rent;
            $itme['alipay_trade_no'] = $itme['alipay_trade_no'] ? $itme['alipay_trade_no'] : $itme['out_order_no'];
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 设置修改收货地址
     * @param Request $request
     * @return false|string
     */
    public function setAddress(Request $request)
    {
        try {
            $orderId = $request->input('orderId', '');
            $realname = $request->input('realname', '');
            $mobile = $request->input('mobile', '');
            $address = $request->input('address', '');
            $prov = $request->input('prov', '');
            $city = $request->input('city', '');
            $area = $request->input('area', '');
            if (!$orderId || !$realname || !$mobile || !$address || !$prov || !$city) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            if (!Order::checkOrderById($orderId)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
            }
            $update = [
                'realname' => $realname,
                'mobile' => $mobile,
                'address' => $address,
                'prov' => $prov,
                'city' => $city,
                'area' => $area,
            ];
            Order::where(['id' => $orderId])->update($update);
            OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '修改收货地址');
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        } catch (\Exception $exception) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
        }
    }

    /**
     * 设置户籍地址
     * @param Request $request
     * @return false|string
     */
    public function setHouseholdAddress(Request $request)
    {
        try {
            $orderId = $request->input('orderId', '');
            $address = $request->input('household_address', '');
            if (!$orderId || !$address) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            if (!Order::checkOrderById($orderId)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
            }
            $update = [
                'household_address' => $address,
            ];
            OrderGoods::where(['order_id' => $orderId])->update($update);
            OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '修改户籍地址');
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        } catch (\Exception $exception) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
        }
    }

    /**
     * 获取租期支付流水
     * @param Request $request
     * @return false|string
     */
    public function getLeaseFlow(Request $request)
    {
        $orderNO = $request->input('orderNo', '');
        if (!$orderNO) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!Order::checkOrderByNo($orderNO)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
        }
        $flow = OtherWithholdLog::getFlow($orderNO);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $flow);
    }

    /**
     * 设置设备编号
     * @param Request $request
     * @return false|string
     */
    public function setDeviceNumber(Request $request)
    {
        try {
            $orderId = $request->input('orderId', '');
            $deviceNumber = $request->input('deviceNumber', '');
            if (!$orderId || !$deviceNumber) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            if (!Order::checkOrderById($orderId)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
            }
            $update = [
                'device_number' => $deviceNumber
            ];
            OrderGoods::where(['order_id' => $orderId])->update($update);
            OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '设置设备编号' . $deviceNumber);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        } catch (\Exception $exception) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
        }
    }

    /**
     * 设置客服备注
     * @param Request $request
     * @return false|string
     */
    public function setOrderRemark(Request $request)
    {
        try {
            $orderId = $request->input('orderId', '');
            $remark = $request->input('remark', '');
            if (!$orderId || !$remark) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            if (!Order::checkOrderById($orderId)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
            }
            $add = [
                'uid' => $this->users['id'],
                'username' => $this->users['username'],
                'create_time' => time(),
                'remark' => $remark,
                'order_id' => $orderId,
            ];
            OrderRemark::insert($add);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '添加成功');
        } catch (\Exception $exception) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '添加失败');
        }
    }

    /**
     * 获取客服备注
     * @param Request $request
     * @return false|string
     */
    public function getOrderRemark(Request $request)
    {
        $orderId = $request->input('orderId', '');
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        if (!$orderId) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!Order::checkOrderById($orderId)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
        }
        $remark = OrderRemark::where(['order_id' => $orderId])->select('username', 'create_time', 'remark')->orderBy('id', 'desc')->paginate($pageSize);
        $remark = obToArray($remark);
        if (isset($remark['data'])) {
            foreach ($remark['data'] as $k => $v) {
                $remark['data'][$k]['create_time'] = dateFormat($v['create_time']);
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $remark);
    }

    /**
     * 获取所有区域
     * @return false|string
     */
    public function getRegion()
    {
        $data = Areas::handle(Areas::GetAllAreasList());
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 账单详情
     * @param Request $request
     * @return false|string
     */
    public function getLeaseInfo(Request $request)
    {
        $orderId = $request->input('orderId', '');
        if (!$orderId) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!Order::checkOrderById($orderId)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
        }
        $leaseDetail = [];
        $order = Order::where(['id' => $orderId])->select('month_total', 'pay_type')->first();
        $order = obToArray($order);
        if ($order['pay_type'] == Order::ORDER_PAY_TYPE_HUABEI) {
            $lease = OrderLease::where(['order_id' => $orderId, 'settle_type' => OrderLease::ORDER_LEASE_SETTLE_STATUS_YES])
                ->whereIn('status', [OrderLease::ORDER_LEASE_STATUS_PAID, OrderLease::ORDER_LEASE_STATUS_REFUNDED, OrderLease::ORDER_LEASE_STATUS_BUYOUT])
                ->select('id', 'which_period', 'rent', 'trade_no', 'status', 'pay_time', 'pay_type', 'settle_type')
                ->first();
            $lease = obToArray($lease);
            if ($lease) {
                $lease['pay_time'] = dateFormat($lease['pay_time']);
                $trans = TransDetail::from('sp_trans_detail as d')
                    ->leftjoin('sp_shop_trans as t', 'd.order_id', 't.order_id')
                    ->select('d.*', 't.amount', 't.service_fee')
                    ->where(['d.order_id' => $orderId])
                    ->orderBy('id', 'desc')
                    ->first();
                $trans = obToArray($trans);
                if ($trans) {
                    $trans['settlement_amount'] = $trans['amount'];
                    $trans['total_charge'] = $trans['service_fee'];
                }
                $lease['trans'] = $trans;
                $lease['which_period'] = "1-" . $order['month_total'];
            }
            $leaseDetail[] = $lease;
        } else {
            $leaseDetail = OrderLease::where(['order_id' => $orderId, 'settle_type' => OrderLease::ORDER_LEASE_SETTLE_STATUS_YES])
                ->whereIn('status', [OrderLease::ORDER_LEASE_STATUS_PAID, OrderLease::ORDER_LEASE_STATUS_REFUNDED, OrderLease::ORDER_LEASE_STATUS_BUYOUT])
                ->select('id', 'which_period', 'rent', 'trade_no', 'status', 'pay_time', 'pay_type', 'settle_type')
                ->get();
            $leaseDetail = obToArray($leaseDetail);
            foreach ($leaseDetail as &$value) {
                $value['pay_time'] = dateFormat($value['pay_time']);
                $trans = TransDetail::where(['order_lease_id' => $value['id']])->orderBy('id', 'desc')->first();
                $trans = obToArray($trans);
                if ($trans) {
                    $shopTrans = ShopTrans::where(['order_lease_id' => $value['id'], 'trans_type' => ShopTrans::ORDER_TRANS_TYPE_SETTLE])->select()->first();
                    $shopTrans = obToArray($shopTrans);
                    $trans['settlement_amount'] = $shopTrans ? $shopTrans['amount'] : '';
                    $trans['total_charge'] = $shopTrans ? $shopTrans['service_fee'] : '';
                }
                $value['trans'] = $trans;
            }
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $leaseDetail);
    }

    /**
     * 发货
     * @param Request $request
     * @return false|string
     */
    public function deliverGoods(Request $request)
    {
        $orderId = $request->input('orderId', '');
        $logistics_name = $request->input('logistics_name', '');
        $logistics_no = $request->input('logistics_no', '');
        $delivery_type = $request->input('delivery_type', '');
        $images = $request->input('images', '');

        if (!$orderId || !$delivery_type || !$images) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!Order::checkOrderById($orderId)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
        }
        if ($images) {
            if (count(explode(',', $images)) > 10) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '发货凭证不能大于10张');
            }
        }

        if ($delivery_type == OrderReturn::ORDER_DELIVERY_TYPE_EXPRESS) {
            if (!$logistics_name || !$logistics_no) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '物流公司和单号不能为空');
            }
            if (!OrderReturn::checkOrderLogisticsNo($logistics_no)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '快递单号已在另一个订单添加，请确认单号填写是否正确');
            }
        }

        $redis = new RedisService();
        $lock = RedisLock::lock($redis, 'orderIdRefund' . $orderId);
        if (!$lock) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '系统繁忙，请稍后再试');
        }
        $order = Order::where(['id' => $orderId, 'status' => OrderService::ORDER_STATUS_PAY_SUCCESS])->lockForUpdate()->select('seller_id', 'uid', 'realname', 'trade_no', 'mobile', 'relation_id')->first();
        $order = obToArray($order);
        if (!$order) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '当前订单状态不支持发货');
        }


        $data = [
            'order_id' => $orderId,
            'logistics_name' => $logistics_name,
            'logistics_no' => $logistics_no,
            'delivery_type' => $delivery_type,
            'images' => $images,
            'status' => OrderReturn::ORDER_EXPRESS_STATUS_DELIVERED,
            'type' => OrderReturn::ORDER_EXPRESS_TYPE_DELIVERY,
            'create_time' => time(),
        ];
        $res = OrderReturn::insert($data);
        if ($res) {
            //更新订单状态
            Order::where(['id' => $orderId])->update(['status' => OrderService::ORDER_STATUS_DELIVER_SUCCESS]);
            OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单发货');


            $where[] = ['o.id', $orderId];
            $where[] = ['m.openId', '<>', ''];
            $where[] = ['ol.out_order_no', '<>', ''];
            $order = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->leftjoin('sp_shop_user_2 as s', 'o.seller_id', 's.member_id')
                ->leftjoin('sp_order_return_2 as or', 'o.id', 'or.order_id')
                ->leftjoin('sp_goods_2 as g', 'og.goods_id', 'g.id')
                ->leftjoin('sp_member_2 as m', 'o.uid', 'm.id')
                ->select(
                    'm.openId', 'ol.out_order_no', 'o.id', 'o.trade_no', 'o.location', 'o.status', 'or.logistics_no', 'or.create_time',
                    'o.is_insurance_choose_custom', 'o.remark', 'o.realname', 'o.mobile as address_mobile', 'o.address', 'o.order_from'
                    , 'og.goods_title', 'og.imgurl', 'og.setmeal_title', 'og.is_buy_out', 'og.device_number', 'og.pact_type', 'og.setmeal_foregift', 'og.setmeal_price'
                    , 'm.mobile',
                )
                ->where($where)->orderBy('id', 'asc')->first();
            $order = obToArray($order);
            if ($order && $order['order_from'] == 'wechat') {
                WechatService::upload_shipping_info($order);
            }
            RedisLock::unlock($redis, 'orderIdRefund' . $orderId);

            SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::KX_SHOPPING);
            SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::CONSUMER);
            SendSmsMessageJob::dispatch(SmsTempEnum::SHIPPED_NOTIFICATION,$orderId);

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
    }

    /**
     * 确认收货
     * @param Request $request
     * @return false|string
     */
    public function confirmGoods(Request $request)
    {

        $orderId = $request->input('orderId','');
        $images = $request->input('images','');
        if(!$orderId || !$images){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }
        if(!Order::checkOrderById($orderId)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未找到订单信息');
        }
        if($images){
            if(count(explode(',',$images)) > 10){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'发货凭证不能大于10张');
            }
        }
        $order = Order::from('sp_order_2 as o')->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')->where(['o.id'=>$orderId,'o.status'=>OrderService::ORDER_STATUS_DELIVER_SUCCESS])->select('o.seller_id','o.trade_no','o.realname','o.mobile','o.month_total','og.pact_type')->first();
        $order = obToArray($order);
        if(!$order){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'当前订单状态不支持确认收货');
        }

        $orderReturn  = OrderReturn::where(['order_id'=>$orderId,'type'=>OrderReturn::ORDER_EXPRESS_TYPE_DELIVERY])->where('status','>',0)->first();
        $orderReturn = obToArray($orderReturn);
        if(!$orderReturn){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'无发货信息');
        }
        if($orderReturn['delivery_type'] == OrderReturn::ORDER_DELIVERY_TYPE_EXPRESS){
            $express_data = LogisticsService::logisticsMessage($orderReturn['logistics_name'],$orderReturn['logistics_no'],$order['mobile']);
            if($express_data&&$express_data['data'][0]['opcode']=='80'){
                $data['info'] = json_encode($express_data);
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'此订单物流信息无法签收');
            }
        }
        $data = [
            'order_id'=>$orderId,
            'sign_proof'=>$images,
            'status'=>OrderReturn::ORDER_EXPRESS_STATUS_SIGNED,
            'confirm_time'=>time(),
        ];
        $res = OrderReturn::where(['id'=>$orderReturn['id']])->update($data);
        if($res){
            //更新订单状态
            $order_data['status'] = OrderService::ORDER_STATUS_CONFIRM_GOODS;
            if($order['pact_type'] != GoodsService::GOODS_PACT_TYPE_GIVE){
                //所有租期已全部支付，状态改为待归还
                if(OrderLease::where([['order_id',$orderId],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']){
                    $order_data['status'] = OrderService::ORDER_STATUS_TOBE_RETURNED;
                }
            }
            Order::where(['id'=>$orderId])->update($order_data);

            OrderLog::addOrderLog($orderId,$this->users['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN,'确认收货');

            AlipayMessageService::sendChangeOrderLeaseMessage($orderId,AlipayMessageService::KX_SHOPPING,'SIGNED');

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'操作成功');
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL,'操作失败');
    }


    /**
     * 补充发货确认收货凭证
     * @param Request $request
     * @return false|string
     */
    public function setOrderVoucher(Request $request)
    {
        $orderId = $request->input('orderId', '');
        $type = $request->input('type', '1'); //1发货 3确认收货
        $images = $request->input('images', '');
        if (!$orderId || !$type || !$images) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }
        if (!Order::checkOrderById($orderId)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
        }
        $orderReturn = OrderReturn::where(['order_id' => $orderId, 'type' => OrderReturn::ORDER_EXPRESS_TYPE_DELIVERY])->select('id', 'images', 'sign_proof', 'status')->first();
        $orderReturn = obToArray($orderReturn);
        if (!$orderReturn) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无发货信息');
        }
        $update = [];
        if ($type == OrderReturn::ORDER_EXPRESS_STATUS_DELIVERED) {
            if (count(explode(',', $orderReturn['images'])) > 9) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '发货凭证不能大于10张');
            }
            if ($orderReturn['images']) {
                $images = $orderReturn['images'] . ',' . $images;
            }
            $update = ['images' => $images];

        }
        if ($type == OrderReturn::ORDER_EXPRESS_STATUS_SIGNED) {
            if ($orderReturn['status'] != OrderReturn::ORDER_EXPRESS_STATUS_SIGNED) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单未确认收货无法上传');
            }
            if (count(explode(',', $orderReturn['sign_proof'])) > 9) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '收货凭证不能大于10张');
            }
            if ($orderReturn['sign_proof']) {
                $images = $orderReturn['sign_proof'] . ',' . $images;
            }
            $update = ['sign_proof' => $images];
        }
        if (!$update) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '凭证补充失败');
        }
        $res = OrderReturn::where(['id' => $orderReturn['id']])->update($update);
        if ($res) {
            OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '补充发货确认收货凭证');
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
    }

    /**
     * 获取物流信息
     * @param Request $request
     * @return false|string
     */
    public function getLogisticInfo(Request $request)
    {
        {
            $orderId = $request->input('orderId', '');
            $type = $request->input('type', '');
            if (!$orderId || !$type) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            if (!Order::checkOrderById($orderId)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
            }
            $orderReturn = OrderReturn::where(['order_id' => $orderId, 'type' => $type])
                ->first();
            $orderReturn = obToArray($orderReturn);
            $mobile = Order::where('id', $orderId)->value('mobile');
            if ($orderReturn) {
                $orderReturn['create_time'] = $orderReturn['create_time'] ? dateFormat($orderReturn['create_time']) : $orderReturn['create_time'];
                $orderReturn['confirm_time'] = $orderReturn['confirm_time'] ? dateFormat($orderReturn['confirm_time']) : $orderReturn['confirm_time'];
                $info = json_decode($orderReturn['info'], true);
                if ($orderReturn['status'] != OrderReturn::ORDER_EXPRESS_STATUS_SIGNED||!$info||!$info['data']) {
                    //未签收
                    if (!empty($orderReturn['logistics_name']) && !empty($orderReturn['logistics_no'])) {
                        $express_data = LogisticsService::logisticsMessage($orderReturn['logistics_name'], $orderReturn['logistics_no'], $mobile);
                        if ($express_data) {
                            OrderReturn::where([['order_id', $orderId], ['type', $type]])
                                ->update(['info' => json_encode($express_data)]);
                        }
                        $orderReturn['info'] = $express_data;
                    }
                } else {
                    if (empty($orderReturn['info']) && !empty($orderReturn['logistics_name']) && !empty($orderReturn['logistics_no'])) {
                        $express_data = LogisticsService::logisticsMessage($orderReturn['logistics_name'], $orderReturn['logistics_no'], $mobile);
                        if ($express_data) {
                            OrderReturn::where([['order_id', $orderId], ['type', $type]])
                                ->update(['info' => json_encode($express_data)]);
                        }
                        $orderReturn['info'] = $express_data;
                    } else {
                        $orderReturn['info'] = json_decode($orderReturn['info']);
                    }

                }
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $orderReturn);
        }
    }

    /**
     * 获取所有物流公司
     * @return false|string
     */
    public function getLogisticAll()
    {
        $express = Express::query()->pluck('name');
        $express = obToArray($express);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $express);
    }

    /**
     * 获取所有订单状态
     * @return false|string
     */
    public function getOrderStatus()
    {
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', OrderService::ORDER_STATUS_NAME_LIST);
    }

    /**
     * 订单列表导出
     * @param Request $request
     * @return false|string
     */
    public function orderListExport(Request $request)
    {
        $data = ExportService::adminOrderListExport($request);

        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无数据');
        }
        $params = $request->input();
        if (isset($params['orderStatus']) && $params['orderStatus']) {
            $params['orderStatus'] = OrderService::ORDER_STATUS_NAME_LIST[$params['orderStatus']];
        }
        // dd($data);
        ExportService::exportFile($params, $data, ExportService::FILE_ORDER_LIST);
    }

    /**
     * 订单分期明细导出
     * @param Request $request
     * @return false|string
     */
    public function orderLeaseExport(Request $request)
    {
        $data = ExportService::adminOrderListLeaseExport($request);
        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无数据');
        }
        $params = $request->input();
        if (isset($params['orderStatus']) && $params['orderStatus']) {
            $params['orderStatus'] = OrderService::ORDER_STATUS_NAME_LIST[$params['orderStatus']];
        }
//         dd($data);
        ExportService::exportFile($params, $data, ExportService::FILE_ORDER_LEASE_LIST);
    }

    /**
     * 发货订单导出
     * @param Request $request
     * @return false|string
     */
    public function orderDeliverListExport(Request $request)
    {
        $data = ExportService::adminOrderDeliverListExport($request);
        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无数据');
        }
        $params = $request->input();
        if (isset($params['orderStatus']) && $params['orderStatus']) {
            $params['orderStatus'] = OrderService::ORDER_STATUS_NAME_LIST[$params['orderStatus']];
        }
        // dd($data);
        ExportService::exportFile($params, $data, ExportService::FILE_ORDER_DELIVER_LIST);
    }

    /**
     * 划扣订单列表提前提醒表-导出
     * @param Request $request
     * @return false|string
     */
    public function orderRemindListExport(Request $request)
    {
        $data = ExportService::adminOrderRemindListBriefExport($request);
        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无数据');
        }
        $params = $request->input();
        if (isset($params['orderStatus']) && $params['orderStatus']) {
            $params['orderStatus'] = OrderService::ORDER_STATUS_NAME_LIST[$params['orderStatus']];
        }
        ExportService::exportFile($params, $data, ExportService::FILE_ORDER_REMIND_BRIEF_LIST);
    }

    /**
     * 花呗订单列表导出
     * @param Request $request
     * @return false|string
     */
    public function orderHuaBeiExport(Request $request)
    {
        $data = ExportService::adminOrderListExport($request, '', [['o.pay_type', Order::ORDER_PAY_TYPE_HUABEI]]);
        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无数据');
        }
        $params = $request->input();
        if (isset($params['orderStatus']) && $params['orderStatus']) {
            $params['orderStatus'] = OrderService::ORDER_STATUS_NAME_LIST[$params['orderStatus']];
        }
        ExportService::exportFile($params, $data, ExportService::FILE_ORDER_LIST, ExportService::FILE_HUABEI_ORDER_LIST);
    }

    /**
     * 买断订单列表导出
     * @param Request $request
     * @return false|string
     */
    public function orderBuyOutListExport(Request $request)
    {
        $data = ExportService::adminOrderListExport($request, '', [['o.status', OrderService::ORDER_STATUS_BUYOUT_PAY]]);
        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无数据');
        }
        $params = $request->input();
        if (isset($params['orderStatus']) && $params['orderStatus']) {
            $params['orderStatus'] = OrderService::ORDER_STATUS_NAME_LIST[$params['orderStatus']];
        }
        ExportService::exportFile($params, $data, ExportService::FILE_ORDER_LIST, ExportService::FILE_BUYOUT_ORDER_LIST);
    }

    /**
     * 签约待支付订单列表导出
     * @param Request $request
     * @return false|string
     */
    public function orderSignedListExport(Request $request)
    {
        $data = ExportService::adminOrderListExport($request, '', [['o.status', OrderService::ORDER_STATUS_SIGN_NOTPAY]]);
        if (!$data) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '无数据');
        }
        $params = $request->input();
        if (isset($params['orderStatus']) && $params['orderStatus']) {
            $params['orderStatus'] = OrderService::ORDER_STATUS_NAME_LIST[$params['orderStatus']];
        }
        ExportService::exportFile($params, $data, ExportService::FILE_ORDER_LIST, ExportService::FILE_SIGNED_ORDER_LIST);
    }

    /**
     * 待支付芝麻信用订单修改为智能合同
     * @param Request $request
     * @return false|string
     */
    public function orderContractUpdate(Request $request)
    {
        $orderId = $request->input('orderId');
        if (!empty($orderId)) {
            $order = Order::where([['id', $orderId], ['status', OrderService::ORDER_STATUS_NOT_PAY]])->select('pay_type', 'flow_id', 'contract_type')->first();
            $order = obToArray($order);
            if (!empty($order)) {
                if ($order['pay_type'] == OrderLease::LEASE_PAY_TYPE_ANTCHAIN) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已修改，请勿重复操作');
                }
                if (!empty($order['flow_id'])) {
                    $orderData['flow_id'] = '';
                }
                $orderData['pay_type'] = Order::ORDER_PAY_TYPE_ANTCHAIN;
                $orderData['contract_type'] = Order::ORDER_CONTRACT_TYPE_ANTCHAIN;
                $res = Order::where('id', $orderId)->update($orderData);
                if ($res) {
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或者状态不是待付款');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }


    /**
     * 订单完结
     */
    public function orderFinish(Request $request)
    {
        $orderId = $request->input('orderId');
        if (!empty($orderId)) {
            $order_res = Order::orderFinish($orderId);
            if ($order_res['status'] == CommonService::HTTP_CODE_SUCCESS) {
                SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::KX_SHOPPING);
                SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::CONSUMER);

                OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单完结');
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $order_res['msg']);
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }

    /**
     * 订单同意归还
     */
    public function orderReturnAgree(Request $request)
    {
        $orderId = $request->input('orderId');
        if (!empty($orderId)) {
            if (Order::where([['id', $orderId], ['status', OrderService::ORDER_STATUS_RETURN_APPLICATION]])->count() > 0) {
                $res = Order::where('id', $orderId)->update(['status' => OrderService::ORDER_STATUS_RETURN_APP_AGREE]);
                if ($res) {
                    OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单同意归还');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不是申请归还');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }

    /**
     * 订单归还审核拒绝
     */
    public function orderReturnRefuse(Request $request)
    {
        $orderId = $request->input('orderId');
        $checkRefuseReason = $request->input('checkRefuseReason');
        if (!empty($orderId) && !empty($checkRefuseReason)) {
            if (Order::where([['id', $orderId], ['status', OrderService::ORDER_STATUS_RETURN_APPLICATION]])->count() > 0) {
                $res = Order::where('id', $orderId)->update(['status' => OrderService::ORDER_STATUS_RETURN_APP_REFUSE, 'check_refuse_reason' => $checkRefuseReason]);
                if ($res) {
                    OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单归还审核拒绝');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不是申请归还');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '审核拒绝原因不能为空');
        }
    }

    /**
     * 订单确认归还
     */
    public function orderConfirmReturn(Request $request)
    {
        $orderId = $request->input('orderId');
        if (!empty($orderId)) {
            if (Order::where([['id', $orderId], ['status', OrderService::ORDER_STATUS_RETURN_DELIVER_SUCCESS]])->count() > 0) {
                $res = Order::where('id', $orderId)->update(['status' => OrderService::ORDER_STATUS_RETURN_CONFIRM_GOODS]);
                if ($res) {
                    OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单确认归还');
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不是归还用户已发货');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }

    /**
     * 获取订单设置页面信息
     */
    public function getOrderSettingData(Request $request)
    {
        $orderId = $request->input('orderId');
        if (!empty($orderId)) {
            $order = Order::from('sp_order_2 as o')->leftjoin('sp_source as s', 'o.order_from', 's.source_code')->leftjoin('sp_order_rate as or', 'o.id', 'or.order_id')->where('o.id', $orderId)->select('o.trade_no', 'o.status', 'o.order_from', 's.source_name', 'or.fixed_amount', 'or.shop_rate')->first();
            $order = obToArray($order);
            if (!empty($order)) {
                $order['status'] = $order['status'] ? OrderService::ORDER_STATUS_NAME_LIST[$order['status']] : '';
                $orderLog = OrderLog::getOrderLogByOrderId($orderId);
                $data['order_data'] = $order;
                $data['order_log'] = $orderLog;
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不是申请归还');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }


    /**
     * 获取订单费率
     */
    public function getOrderRate(Request $request)
    {
        $orderId = $request->input('orderId');
        if (!empty($orderId)) {
            $order_rate = OrderRate::where('order_id', $orderId)->select('fixed_amount', 'shop_rate', 'smartcontract_amount', 'realname_amount', 'risk_amount', 'platform_rate', 'withhold_rate', 'file_rate', 'financing_rate')->first();
            $order_rate = obToArray($order_rate);
            if (!empty($order_rate)) {
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $order_rate);
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单费率不存在');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }

    /**
     * 设置订单费率
     */
    public function settingOrderRate(Request $request)
    {
        $orderId = $request->input('orderId');
        $smartcontract_amount = $request->input('smartcontract_amount', 0);
        $realname_amount = $request->input('realname_amount', 0);
        $risk_amount = $request->input('risk_amount', 0);
        $platform_rate = $request->input('platform_rate', 0);
        $withhold_rate = $request->input('withhold_rate', 0);
        $file_rate = $request->input('file_rate', 0);
        $financing_rate = $request->input('financing_rate', 0);
        if (!empty($orderId)) {
            if (OrderRate::where('order_id', $orderId)->count() > 0) {
                $order_rate['smartcontract_amount'] = $smartcontract_amount;
                $order_rate['realname_amount'] = $realname_amount;
                $order_rate['risk_amount'] = $risk_amount;
                $order_rate['platform_rate'] = $platform_rate;
                $order_rate['withhold_rate'] = $withhold_rate;
                $order_rate['file_rate'] = $file_rate;
                $order_rate['financing_rate'] = $financing_rate;
                $order_rate['fixed_amount'] = $smartcontract_amount + $realname_amount + $risk_amount;
                $order_rate['shop_rate'] = $platform_rate + $withhold_rate + $file_rate + $financing_rate;
                $order_rate['update_time'] = date('Y-m-d H:i:s');
                $res = OrderRate::where('order_id', $orderId)->update($order_rate);
                if (!empty($res)) {
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败，请稍后再试');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单费率不存在');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要操作的订单');
        }
    }


    /**
     *  拒绝订单关闭
     */
    public function orderRefuse(Request $request)
    {
        $orderId = $request->input('orderId');
        $redis = new RedisService();
        $lock = RedisLock::lock($redis, 'orderIdRefund' . $orderId);
        if (!$lock) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '系统繁忙，请稍后再试');
        }
        $uid= Order::query()->where('id', $orderId)->value('uid');
        if (!empty($uid)) {
                $add = [
                    'uid' => $this->users['id'],
                    'username' => $this->users['username'],
                    'create_time' => time(),
                    'remark' => $this->users['username'] . '拉黑用户',
                    'order_id' => $orderId
                ];
                OrderRemark::insert($add);

                Redis::setex('user_order_limit_crate_order_black_'.$uid,86400*30,1);

                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '取消成功');
            } else {
               return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
           }

    }

    /**
     * 待支付订单关闭
     */
    public function orderClose(Request $request)
    {
        $orderId = $request->input('orderId');
        // dd($orderId);
        $redis = new RedisService();
        $lock = RedisLock::lock($redis, 'orderIdRefund' . $orderId);
        if (!$lock) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '系统繁忙，请稍后再试');
        }
        if (!empty($orderId)) {
            $order_res = Order::noPayOrderCancel($orderId, false, false, $this->users['username']);
            if ($order_res['status'] == CommonService::HTTP_CODE_SUCCESS) {
                $add = [
                    'uid' => $this->users['id'],
                    'username' => $this->users['username'],
                    'create_time' => time(),
                    'remark' => $this->users['username'] . '关闭订单',
                    'order_id' => $orderId
                ];
                OrderRemark::insert($add);
                OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单关闭');
                RedisLock::unlock($redis, 'orderIdRefund' . $orderId);
                SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::KX_SHOPPING);
                SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::CONSUMER);

                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '取消成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $order_res['msg']);
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     * 更新身份证证件
     * @param Request $request
     * @return false|string
     */
    public function updateMemberCard(Request $request)
    {
        if (empty($request['order_id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '请选择订单');
        }
        $member_id = order::where('id', $request['order_id'])->value('uid');
        $res = MemberOther::where('id', $member_id)->update(['idcard_front' => $request['front'], 'idcard_back' => $request['back']]);
        if ($res) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');

        }
    }

    /**
     * 待支付订单批量关闭
     */
    public function orderBatchClose(Request $request)
    {
        $orderIds = $request->input('orderIds');
        // dd($orderId);
        if (!empty($orderIds)) {
            $orderIds = explode(',', $orderIds);
            if (count($orderIds) > 10) {
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '最多批量操作10条');
            }
            $order_res = Order::noPayOrderBatchCancel($orderIds);

            if ($order_res['status'] == CommonService::HTTP_CODE_SUCCESS) {

                if (count($orderIds) > 0) {
                    foreach ($orderIds as $ra) {
                        //添加备注
                        $add = [
                            'uid' => $this->users['id'],
                            'username' => $this->users['username'],
                            'create_time' => time(),
                            'remark' => $this->users['username'] . '关闭订单',
                            'order_id' => $ra
                        ];
                        OrderRemark::insert($add);
                        OrderLog::addOrderLog($ra, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单关闭');


                        SendChangeOrderMessage::dispatch($ra,AlipayMessageService::KX_SHOPPING);
                        SendChangeOrderMessage::dispatch($ra,AlipayMessageService::CONSUMER);


                    }
                }

                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '关闭订单成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, $order_res['msg']);
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }

    /**
     * 修改订单物流信息
     */
    public function editOrderExpress(Request $request)
    {
        $orderId = $request->input('orderId');
        $editCode = $request->input('editCode');
        $editValue = $request->input('editValue');
        if (empty($orderId) || empty($editCode) || empty($editValue)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }
        if (!Order::checkOrderById($orderId)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
        }
        $orderReturn = OrderReturn::where('order_id', $orderId)->select('id', 'logistics_name', 'logistics_no', 'status')->first();
        $orderReturn = obToArray($orderReturn);
        if (!empty($orderReturn)) {
            if ($orderReturn[$editCode] == $editValue) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据未修改，请修改后再提交');
            }
            if ($orderReturn['status'] == OrderReturn::ORDER_EXPRESS_STATUS_SIGNED) {
                $data['status'] = OrderReturn::ORDER_EXPRESS_STATUS_TRANSIT;
            }
            $data[$editCode] = $editValue;
            $res = OrderReturn::where('id', $orderReturn['id'])->update($data);
            $log_content = '修改订单物流信息：' . $orderReturn[$editCode] . '更改为' . $editValue;
            $log_res = OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, $log_content);
            if ($res !== false && $log_res !== false) {
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败，请稍后再试');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单发货信息不存在，请确认后再操作');
        }
    }

    /**
     * 获取剩余押金
     */
    public function getSurplusDeposit(Request $request)
    {
        $orderId = $request->input('orderId');
        if (!empty($orderId)) {
            $order = Order::where([['id', $orderId], ['status', '>', 10]])->select('id', 'mini_id', 'alipay_trade_no', 'rights_auth_no', 'trade_no')->first();
            $order = obToArray($order);
            if (!empty($order)) {
                $params['alipayTradeNo'] = $order['alipay_trade_no'];
                $params['authNo'] = $order['rights_auth_no'];
                $orderInfo = AlipayService::alipayPreQuery($order['mini_id'], $params);
                if ($orderInfo['status']) {
                    $orderRes = $orderInfo['data'];
                    if ($orderRes['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
                        $data['rest_amount'] = $orderRes['rest_amount'];
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
                    } else {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单授权信息查询失败');
                    }
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单授权信息查询失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单信息不存在');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单信息不存在，请确认后再操作');
        }
    }

    /**
     * 扣除押金
     */
    public function deductDeposit(Request $request)
    {
        $orderId = $request->input('orderId');
        $amount = $request->input('amount');
        if (!empty($orderId) && !empty($amount)) {
            $order = Order::from('sp_order_2 as o')
                ->select('o.mini_id', 'o.trade_no', 'o.rights_auth_no', 'o.alipay_trade_no', 'o.payer_user_id', 'og.goods_title', 'su.shopname', 'o.month_total', 'o.begin_time', 'o.end_time')
                ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                ->leftjoin('sp_shop_user_2 as su', 'o.seller_id', 'su.member_id')
                ->where('o.id', $orderId)
                ->first();
            $order = obToArray($order);
            if (!empty($order)) {

                $miniId = $order['mini_id'];

                $params['alipayTradeNo'] = $order['alipay_trade_no'];
                $params['authNo'] = $order['rights_auth_no'];

                $orderInfo = AlipayService::alipayPreQuery($miniId, $params);

                if ($orderInfo['status']) {
                    $orderRes = $orderInfo['data'];
                    if ($orderRes['code'] == AlipayService::ALIPAY_SUCCESS_CODE) {
                        if ($orderRes['rest_amount'] >= $amount) {

                            $payData['miniId'] = $miniId;
                            $payData['orderNo'] = $order['trade_no'];
                            $payData['authNo'] = $order['rights_auth_no'];
                            $payData['subject'] = '预授权转支付' . $order['goods_title'];
                            $payData['totalAmount'] = $amount;
                            $payData['userAlipayUId'] = $order['payer_user_id'];
                            $payData['orderDescribe'] = '预授权解冻转支付' . $order['goods_title'];
                            $payData['notifyUrl'] = config('alipay.callbackDomain') . CommonService::NOTICE_XXZ_URL_DEPOSIT;

                            $payRes = AlipayService::deductDeposit($payData);

                            if ($payRes['status']) {
                                //查询是否有待履约的芝麻信用记录
                                $log_out_trade_no = isset($payRes['data']['out_trade_no']) ? $payRes['data']['out_trade_no'] : 0;
                                $log_trade_no = isset($payRes['data']['trade_no']) ? $payRes['data']['trade_no'] : 0;
                                DB::beginTransaction();

                                OtherWithholdLog::orderWithholdLog($order['trade_no'], 0, $log_out_trade_no, $log_trade_no, $payRes['data'], OtherWithholdLog::PAY_TYPE_DEPOSIT, $payRes['status'], $this->users['id']);

                                $OrderLease = OrderLease::where('order_id', $orderId)->where('status', '<>', 1)->orderBy('id', 'asc')->get();
                                $OrderLease = obToArray($OrderLease);
                                $receipt_amount = $payRes['data']['receipt_amount'];
                                if (!empty($OrderLease)) {
                                    foreach ($OrderLease as $key => $value) {
                                        if ($receipt_amount <= 0) {
                                            break;
                                        }
                                        if (($value['rent'] - $value['paid_rent']) > $receipt_amount) {
                                            $partial = [];
                                            $partial['out_trade_no'] = $order['trade_no'];;
                                            $partial['trade_no'] = $payRes['data']['trade_no'];
                                            $partial['out_order_no'] = $payRes['data']['trade_no'];
                                            $partial['pay_time'] = strtotime($payRes['data']['gmt_payment']);
                                            $partial['status'] = OrderLease::ORDER_LEASE_STATUS_PAID;
                                            $partial['pay_type'] = OrderLeasePartial::PAY_ALIPAY;
                                            $partial['lease_id'] = $value['id'];
                                            $partial['reason'] = '押金扣除';
                                            $partial['partial_amount'] = $receipt_amount;
                                            OrderLeasePartial::insert($partial);
                                            OrderLease::where('id', $value['id'])->increment('paid_rent', $receipt_amount);

                                            OtherWithholdLog::orderWithholdLog($order['trade_no'], $value['id'], $payRes['data']['out_trade_no'], $payRes['data']['trade_no'], $payRes['data'], OtherWithholdLog::PAY_TYPE_ZM, true, 1, $receipt_amount);
                                            break;
                                        } else if (($value['rent'] - $value['paid_rent']) <= $receipt_amount) {
                                            $receipt_amounta = $value['rent'] - $value['paid_rent'];
                                            $leaseSave = [];
                                            $leaseSave['alipay_trade_no'] = $payRes['data']['trade_no'];
                                            $leaseSave['trade_no'] = $payRes['data']['trade_no'];
                                            $leaseSave['out_order_no'] = $payRes['data']['out_trade_no'];
                                            $leaseSave['pay_time'] = strtotime($payRes['data']['gmt_payment']);
                                            $leaseSave['status'] = OrderLease::ORDER_LEASE_STATUS_PAID;
                                            $leaseSave['pay_type'] = OrderLease::LEASE_PAY_TYPE_ZM;
                                            OrderLease::where('id', $value['id'])->increment('paid_rent', $receipt_amounta);
                                            OrderLease::where('id', $value['id'])->where('status', '<>', 1)->update($leaseSave);
                                            OtherWithholdLog::orderWithholdLog($order['trade_no'], $value['id'], $payRes['data']['out_trade_no'], $payRes['data']['trade_no'], $payRes['data'], OtherWithholdLog::PAY_TYPE_ZM, true, 1, $receipt_amounta);
                                            $receipt_amount = bcsub($receipt_amount, $value['rent'] - $value['paid_rent'], 2);
                                        }

                                    }
                                }

//                                $data['order_id'] = $orderId;
//                                $data['which_period'] = $order['month_total']+1;
//                                $data['begin_time'] = strtotime(date('Y-m-d',strtotime($order['end_time'])));
//                                $data['end_time'] = $data['begin_time']+24*3600;
//                                $data['rent'] = $payRes['data']['receipt_amount'];
//                                $data['create_time'] = strtotime($payRes['data']['gmt_payment']);
//                                $data['paid_rent'] = $payRes['data']['total_amount'];
//                                $data['pay_type'] = OrderLease::LEASE_PAY_TYPE_PREPAYMENT;
//                                $data['pay_time'] = strtotime($payRes['data']['gmt_payment']);
//                                $data['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
//                                $data['alipay_trade_no'] =$payRes['data']['trade_no'];
//                                $data['trade_no'] =$payRes['data']['trade_no'];
//                                $addRes = OrderLease::insert($data);

                                if ($payRes['status']) {
                                    DB::commit();
                                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '代扣成功');
                                } else {
                                    DB::rollBack();
                                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '代扣失败');
                                }
                            } else {
                                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '代扣失败');
                            }
                        } else {
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '扣款金额不能大于剩余冻结金额');
                        }
                    } else {
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单授权信息查询失败');
                    }
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单授权信息查询失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单信息不存在');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }
    }

    /**
     * 编辑订单数据
     * @param Request $request
     * @return false|string
     */
    public function editOrderData(Request $request)
    {

        $data = $request->input();
        $num = $data['num'];
        if ($request['down_payment'] > $request['setmeal_foregift']) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '首付金额不能大于市场价'];
        }
        $orderId = $request['orderId'];
        $status = Order::where('id', $orderId)
            ->value('status');
        if ($status > 4) {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '当前订单状态不支持修改'];
        }
        if ($num == 4) {
            Order::editOrderData($data, $this->users);
        } else if ($num == 2) {
            //修改租期类型
            OrderGoods::editOrderData($data, $this->users['username']);
            //修改每期租金等等
            $res = Order::editLeaseRents($data);
            //修改总租金
            if ($res) {
                OrderLease::editLeaseRents($data);
            }

        }

        return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '修改成功'];
    }

    /**
     * 获取每期租金数据
     * @return false|string
     */
    public function getLeaseRent(Request $request)
    {

        $orderId = $request->input('orderId', '');

        $data = OrderLease::getLeaseRent($orderId);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 获取订单编辑数据
     * @return false|string
     */
    public function getOrderData()
    {
        $data['pact_type'] = GoodsService::GOODS_PACT_TYPE_NAME_LIST;
        $data['month_total'] = OrderService::ORDER_MONTH_LIST;
        $data['insurance_list'] = GoodsService::GOODS_INSURANCE_LIST_SHOW;
        $data['rent_list'] = GoodsService::GOODS_RENT_LIST_SHOW;
        $data['lease_day'] = OrderService::ORDER_LEASE_DAY_LIST;
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 导出签收凭证word
     */
    public function downloadWord(Request $request)
    {
        $orderId = $request->input('orderId');
        $export = $request->input('export');
        if (!empty($orderId)) {

            if ($export) {
                $file = Order::downloadWord($orderId);
                return response()->download($file);
            }

        } else {

            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');

        }
    }


    /**
     * 订单雷达风控大数据-布尔
     */

    public function getRadarData(Request $request)
    {$input = $request->input();

        if(!empty($input['orderId'])){


            $risk_data = OrderRadarBoolea::getRiskData($input['orderId']);

            //有则输出，无则添加
            if($risk_data){

                $risk_data['resp_data'] = json_decode($risk_data['result'])->data;

                $risk_data['risk_probe']=json_decode($risk_data['risk_probe_result']);

                // $risk_data['result2'] = json_decode($risk_data['result2']);

            }else{
                $order = Order::from('sp_order_2 as o')->where('o.id',$input['orderId'])
                    ->leftjoin('sp_member_2 as m','m.id','o.uid')
                    ->select('m.cert_name','m.cert_no','m.mobile','o.id as orderId')
                    ->first();
//                $flowId=AuthenticLog::where('order_id',$input['orderId'])->orderbY('id','desc')->where('status',1)->value('certify_id');
//
//                if(empty($order['esign_user_id'])||empty($order['esign_seal_id'])||!$flowId){
//                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'用户未完成人脸识别');
//                }

                //全景雷达
                $risk_data = RiskService::radarData($order);

                OrderRadarBoolea::setRiskData($input['orderId'],$risk_data,$input['cert_name'],$input['mobile'],$input['cert_no']);

                $risk_data['cert_name'] = $input['cert_name'];

                $risk_data['mobile'] = $input['mobile'];

                $risk_data['cert_no'] = $input['cert_no'];

                $risk_data['order_id'] = $input['orderId'];

                // $t = $risk_data['timestamp'];

                // $times = strtotime(substr($t,0,4).'-'.substr($t,4,2).'-'.substr($t,6,2).' '.substr($t,8,2).':'.substr($t,10,2).':'.substr($t,12,2));

                $risk_data['start_at'] = date('Y-m-d H:i:s');

                $risk_data['end_at'] =  date('Y-m-d H:i:s',time()+7*24*60*60);

                $risk_data['resp_data'] = $risk_data['data'];

                // 探针雷达

                // $zhen_data = RiskService::zhenData($input);

                $online_data = [];

                // $risk_data['result2'] = $online_data['result2'] = $zhen_data['resp_code'] == 'SW0000' ? $zhen_data['resp_data'] : $zhen_data['resp_code'];


                $online_data['user_type'] = OrderService::RISK_USER_TYPE_ADMIN; //管理员查看
                // var_dump($online_data);

                OrderRadarBoolea::editRiskData($input['orderId'],$online_data);


            }

            $res = obToArray($risk_data);

//            $data['cert_name']='邴建礼';
//            $data['mobile']='15393103307';
//            $data['cert_no']='620123199407216118';


            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$res);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请选择要风控的订单');
        }

    }

    /**
     * 更新订单设备锁
     * @param Request $request
     * @return false|string
     */
    public function updateOrderLock(Request $request)
    {
        if (empty($request['order_id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '请选择订单');
        }
        $order = order::where('id', $request['order_id'])->select('id', 'is_lock')
            ->first();
        $order = $order ? $order->toArray() : [];
        if (empty($order)) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '请选择订单');
        }
        $res = Order::where('id', $order['id'])->update(['is_lock' => $order['is_lock'] ? 0 : 1]);
        if ($res) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');

        }
    }

    /**
     * 订单学历风控大数据
     */
    public function getEduData(Request $request)
    {
        $input = $request->input();

        if (!empty($input['cert_no'])) {

            $risk_data = OrderEduBoolea::getRiskData($input['cert_no']);

            //有则输出，无则添加
            if ($risk_data) {

                $risk_data['resp_data'] = $risk_data['result'] ? json_decode($risk_data['result'])->resp_data : $risk_data['result'];

                $risk_data['result2'] = $risk_data['result2'] ? json_decode($risk_data['result2']) : $risk_data['result2'];

            } else {
                //学历
                $eduNum = $input['eduNum'];

                $risk_data = [];
                $risk_data2 = [];
                if ($eduNum) {
                    //详细学历
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '暂无此服务');
                    $risk_data['result2'] = [];
                    $risk_data['resp_data'] = [];
                } else {
                    //简单学历
                    $risk_data = RiskService::eduData($input);
                    $risk_data['result2'] = [];
                }

                //保存
                OrderEduBoolea::setRiskData($risk_data, $risk_data2, $input['cert_name'], $input['mobile'], $input['cert_no'], $eduNum);

                $risk_data['cert_name'] = $input['cert_name'];

                $risk_data['mobile'] = $input['mobile'];

                $risk_data['cert_no'] = $input['cert_no'];

                $risk_data['edu_num'] = $input['eduNum'];


                $risk_data['start_at'] = date('Y-m-d H:i:s');

                $online_data['user_type'] = OrderService::RISK_USER_TYPE_ADMIN; //管理员查看
                // var_dump($online_data);

                OrderEduBoolea::editRiskData($input['cert_no'], $online_data);

            }

            $res = obToArray($risk_data);

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $res);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要风控的订单');
        }

    }

    /**
     * 订单风控大数据
     */
    public function getRiskData(Request $request)
    {
        $input = $request->input();
        $uid=Order::where('id',$input['orderId'])->value('uid');
        $input['uid']=$uid;
        $member=MemberOther::where('id',$uid)->select('cert_no','mobile','cert_name')->first();
        if(empty($member['cert_no'])||empty($member['mobile'])||empty($member['cert_name'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'用户三要素信息不完整');
        }
        $input['cert_no']=$member['cert_no'];
        $input['mobile']=$member['mobile'];
        $input['cert_name']=$member['cert_name'];
        if(!empty($input['orderId'])){

            $risk_data = OrderRiskBoolea::getRiskData($input['orderId']);

            //有则输出，无则添加
            if($risk_data){

                $risk_data['result'] = json_decode($risk_data['result']);

                $risk_data['resp_data'] = $risk_data['result']->resp_data;

            }else{
                if(Redis::get('getRiskCustomData_order_id'.$input['orderId'])){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请不要频繁点击');
                }
                Redis::setEx('getRiskCustomData_order_id'.$input['orderId'], 30, 1);


                $risk_data = RiskService::booleData($input);
                OrderRiskBoolea::setRiskData($input['orderId'],$risk_data);

                $risk_data['order_id'] = $input['orderId'];

                $t = $risk_data['timestamp'];


                $risk_data['start_at'] = date('Y-m-d H:i:s');

                $risk_data['end_at'] =  date('Y-m-d H:i:s',time()+7*24*60*60);

                $online_data = [];

                $online_data['user_type'] = OrderService::RISK_USER_TYPE_ADMIN; //管理员查看

                OrderRiskBoolea::editRiskData($input['orderId'],$online_data);
            }


            $res = obToArray($risk_data);

            $online = [
                '1'=>'0-3个月',
                '2'=>'3-6个月',
                '3'=>'6个月-1年',
                '4'=>'1年-2年',
                '5'=>'2年以上',
                '0'=>'查无记录',
                '-1'=>'不支持该运营商',
                '999'=>'手机状态异常（注:1、销号6月以上；2、携号转网；3、未放出去的号码）或者非本网手机号码',
            ];

            $goods_type = [
                '0'=>'其他',
                '1'=>'游戏电玩',
                '2'=>'娱乐影⾳',
                '3'=>'电脑平板',
                '4'=>'⼿机优选'
            ];

            $new_old = [
                '0'=>'全新',
                '1'=>'二手'
            ];
            $res['resp_data']['ident_info_dict']['time_online'] = $online[$res['resp_data']['ident_info_dict']['time_online']];

            $res['resp_data']['base_info']['goods_type'] = $goods_type[$res['resp_data']['base_info']['goods_type']];

            $res['resp_data']['base_info']['status'] = $new_old[$res['resp_data']['base_info']['status']];

            $resLegal=MemberLegal::where('uid',$uid)->value('result');
            $detail=json_decode($resLegal,true)['data'];
            $regel=[];
            if($detail['consumptionRestrictionList']){
                foreach ($detail['consumptionRestrictionList'] as $k=>$v){
                    $sx_des='发布时间:'.$v['issueDate'].';';
                    $sx_des.='案件编号:'.$v['caseNumber'].';';
                    $sx_des.='立案时间:'.$v['fileDate'].';';
                    $sx_des.='执行法院:'.$v['executiveCourt'].';';
                    $regel[]=['index'=>'是限高被执行人','des'=>$sx_des];
                }
            }
            if($detail['breachCaseList']){
                foreach ($detail['breachCaseList'] as $k=>$v){
                    $sx_des='案号:'.$v['caseNumber'].';';
                    $sx_des.='发布日期:'.$v['issueDate'].';';
                    $sx_des.='立案时间:'.$v['fileDate'].';';
                    $sx_des.='被执行人的履行情况:'.$v['fulfillStatus'].';';
                    $sx_des.='判决金额:'.$v['estimatedJudgementAmount'].';';
                    $sx_des.='失信被执行人行为具体情形:'.$v['concreteDetails'].';';
                    $sx_des.='执行法院:'.$v['executiveCourt'].';';
                    $sx_des.='出执行依据单位:'.$v['enforcementBasisOrganization'].';';
                    $regel[]=['index'=>'是失信被执行人','des'=>$sx_des];
                }
            }

            if($detail['lawsuitStat']['implement']['cases']){
                foreach ($detail['lawsuitStat']['implement']['cases'] as $k=>$v){
                    $sx_des='案件类型:'.$v['n_ajlx'].';';
                    $sx_des.='案件标识:'.$v['n_ajbs'].';';
                    $sx_des.='经办法院:'.$v['n_jbfy'].';';
                    $sx_des.='法院所属层级:'.$v['n_jbfy_cj'].';';
                    $sx_des.='案件进展阶段:'.$v['n_ajjzjd'].';';
                    $sx_des.='起诉标的金额等级:'.$v['n_jabdje_level'].';';
                    $sx_des.='起诉标的金额:'.$v['n_jabdje'].';';
                    $sx_des.='结案案由:'.$v['n_jaay'].';';
                    $sx_des.='案件类型:'.$v['n_ajlx'].';';
                    $sx_des.='诉讼地位:'.$v['n_ssdw'].';';
                    $sx_des.='判决结果:'.$v['c_gkws_pjjg'].';';
                    $regel[]=['index'=>'执行案件','des'=>$sx_des];
                }

            }
            if($detail['lawsuitStat']['civil']['cases']){
                foreach ($detail['lawsuitStat']['civil']['cases'] as $k=>$v){
                    foreach ($v['c_dsrxx'] as $ka=>$v1){
                        $v['c_dsrxx'.$ka]=implode(',', $v1);
                    }
                    $values =implode(',', array_values($v));
                }
                $regel[]=['index'=>'民事案件','des'=>$values];
            }
            if($detail['lawsuitStat']['criminal']['cases']){
                foreach ($detail['lawsuitStat']['criminal']['cases'] as $k=>$v){
                    foreach ($v['c_dsrxx'] as $ka=>$v1){
                        $v['c_dsrxx'.$ka]=implode(',', $v1);
                    }
                    $v['c_dsrxx']=implode(',', array_values($v['c_dsrxx']));
                    $values =implode(',', array_values($v));
                }
                $regel[]=['index'=>'刑事案件','des'=>$values];

            }
            if($detail['lawsuitStat']['administrative']['cases']){
                foreach ($detail['lawsuitStat']['administrative']['cases'] as $k=>$v){
                    foreach ($v['c_dsrxx'] as $ka=>$v1){
                        $v['c_dsrxx'.$ka]=implode(',', $v1);
                    }
                    $v['c_dsrxx']=implode(',', array_values($v['c_dsrxx']));
                    $values =implode(',', array_values($v));
                }
                $regel[]=['index'=>'行政案件','des'=>$values];
            }
            if($detail['lawsuitStat']['preservation']['cases']){
                foreach ($detail['lawsuitStat']['preservation']['cases'] as $k=>$v){
                    foreach ($v['c_dsrxx'] as $ka=>$v1){
                        $v['c_dsrxx'.$ka]=implode(',', $v1);
                    }
                    $v['c_dsrxx']=implode(',', array_values($v['c_dsrxx']));
                    $values =implode(',', array_values($v));
                }
                $regel[]=['index'=>'非诉保全审查案件','des'=>$values];
            }
            if($detail['lawsuitStat']['bankrupt']['cases']){
                foreach ($detail['lawsuitStat']['bankrupt']['cases'] as $k=>$v){
                    foreach ($v['c_dsrxx'] as $ka=>$v1){
                        $v['c_dsrxx'.$ka]=implode(',', $v1);
                    }
                    $v['c_dsrxx']=implode(',', array_values($v['c_dsrxx']));
                    $values =implode(',', array_values($v));
                }
                $regel[]=['index'=>'强制清算与破产案件','des'=>$values];
            }

            $res['cert_name'] = $input['cert_name'];

            $res['mobile'] = $input['mobile'];

            $res['cert_no'] = $input['cert_no'];

            $res['order_id'] = $input['orderId'];

            $res['resp_data']['onlineTime']=XinyanService::onlineTime($input);
            $res['resp_data']['threeElements']=XinyanService::threeElements($input);

            $res['resp_data']['lagal'] =$regel ;

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$res);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请选择要风控的订单');
        }
    }

    /**
     * 获取签署时的人脸
     * @param Request $request
     * @return false|string
     */
    public function getSignFace(Request $request)
    {
        try {
            $orderId = $request->input('orderId', '');
            if (!$orderId) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            $order = Order::where('id', $orderId)->select('uid', 'face_flow_id')->first()->toArray();
            if (!$order) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
            }
//            $user= MemberOther::where('id',$order['uid'])->select('id','esign_user_id')->first()->toArray();

            $data = EsignService::selectFaceAuth($order['face_flow_id']);

            $url = '';

            if (isset($data['indivInfo']['facePhotoUrl']) && !empty($data['indivInfo']['facePhotoUrl'])) {
                $val = file_get_contents($data['indivInfo']['facePhotoUrl']);

                $url = $val;
//                     $uploud_res = AlipayService::upload($fileName,$path);
//                     if($uploud_res['status']){
//                         if(file_exists($path)){
//                             unlink($path);
//                         }
//                     }
            }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $url);
        } catch (\Exception $exception) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '获取签署人脸照片失败');
        }
    }

    /**
     * 订单审核通过
     */
    public function orderCheckPass(Request $request)
    {
        $orderId = $request->input('orderId');

        if (!empty($orderId)) {
            OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '订单审核通过');
            if (Order::where([['id', $orderId], ['status', OrderService::ORDER_STATUS_SIGN_NOCHECK]])->count() > 0) {
                //订单征信-上征信-担保放款

                $order = Order::from('sp_order_2 as o')->where('o.id', $orderId)
                    ->leftjoin('sp_order_credit as c', 'c.order_id', 'o.id')
                    ->leftjoin('sp_member_2 as u', 'o.uid', 'u.id')
                    ->leftjoin('sp_shop_user_2 as su', 'o.seller_id', 'su.member_id')
                    ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
                    ->leftjoin('sp_goods_2 as g', 'og.goods_id', 'g.id')
                    ->select(
                        'o.id', 'o.mini_id', 'o.trade_no', 'o.begin_time', 'o.zulinbao_order_id', 'o.end_time', 'o.pact_url_3', 'o.uid', 'o.seller_id', 'o.is_insurance_choose', 'o.is_insurance_choose_custom',
                        'o.flow_id', 'o.mobile', 'o.user_email', 'o.sign_num', 'o.address', 'o.rent_total', 'o.month_total', 'o.amount', 'o.realname', 'o.rent_total',
                        'o.foregift', 'o.status', 'o.prov', 'o.city', 'o.area', 'o.sign_status', 'o.is_rent_choose'
                        , 'c.platformLoanNo', 'o.create_time', 'og.lease_day','og.goods_name'
                        , 'u.ant_user_id', 'u.mobile as user_mobile', 'u.id as x_user_id', 'u.cert_name', 'u.user_id', 'u.cert_no', 'u.esign_user_id'
                        , 'u.idcard_front', 'u.idcard_back', 'og.pact_type', 'og.is_buy_out', 'og.goods_title', 'og.setmeal_title', 'og.lease_set', 'og.setmeal_price', 'og.setmeal_foregift',
                        'og.goods_id', 'og.setmeal_id', 'og.id as order_goods_id', 'og.spec_id', 'og.lease_price', 'og.lease_time', 'og.website_price', 'og.start_date'
                        , 'su.mechanism', 'su.faname', 'su.shopname', 'su.contact_tel', 'su.company', 'su.company_area', 'su.companyid', 'su.id as shop_user_id'
                        , 'su.ant_user_id as mer_ant_id', 'u.openId'
                        , 'g.new_grade')
                    ->first();
                $order = $order ? $order->toArray() : [];
                //租赁宝plus

                if (!strstr($order['address'], '省') && !strstr($order['address'], '市')) {
                    $address = $order['prov'] . $order['city'] . $order['area'] . $order['address'];
                } else {
                    $address = $order['address'];
                }
                if (mb_strlen($address) > 80) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '用户收货地址过长，请手动修改下');
                }



                //获取合同签署地址
                if (empty($order['openId'])) {
                        $res = AntchainAtoService::syncBehindOrder($order);
                        if ($res && $res['resultCode'] != 'OK') {
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, $res['resultMsg']);
                        }
                }

                OrderLog::addOrderLog($orderId,$this->users['id'],OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN,'订单审核通过');

                $res = Order::where('id', $orderId)->update(['status' => OrderService::ORDER_STATUS_SIGN_NOTPAY]);

                if ($res) {
                    // 发送订单状态变更消息
                    SendChangeOrderMessage::dispatch($orderId,AlipayMessageService::CONSUMER);
                    SendSmsMessageJob::dispatch(SmsTempEnum::ORDER_APPROVED,$orderId);
                    SendSmsMessageJob::dispatch(SmsTempEnum::CONFIRM_ORDER_INFO,$orderId)->delay(1800);
                    SendSmsMessageJob::dispatch(SmsTempEnum::CONFIRM_ORDER_INFO,$orderId)->delay(86400);
                    SendSmsMessageJob::dispatch(SmsTempEnum::CONFIRM_ORDER_INFO,$orderId)->delay(86400*3);

                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在或订单状态不是待审核');
            }
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '缺少参数');
        }
    }

    /**
     * 获取供应商数据
     * @return false|string
     */
    public function getShopUser()
    {

        $data = ShopUser::getShopUsers();

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $data);
    }

    /**
     * 设定拿货价
     * @param Request $request
     * @return false|string
     */
    public function setAcquisitionPrice(Request $request)
    {
        try {
            $orderId = $request->input('orderId', '');
            $acquisitionPrice = $request->input('acquisition_price', '');
            if (!$orderId || $acquisitionPrice < 0) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            if (!Order::checkOrderById($orderId)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
            }
            $update = [
                'acquisition_price' => $acquisitionPrice
            ];
            OrderGoods::where(['order_id' => $orderId])->update($update);
            OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '设置拿货价' . $acquisitionPrice);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        } catch (\Exception $exception) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
        }
    }

    /**
     * 设定租赁押金
     * @param Request $request
     * @return false|string
     */
    public function setCashPledgePrice(Request $request)
    {
        try {
            $orderId = $request->input('orderId', '');
            $cash_pledge = $request->input('cash_pledge', '');
            if (!$orderId || $cash_pledge < 0) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            if (!Order::checkOrderById($orderId)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未找到订单信息');
            }
            $update = [
                'cash_pledge' => $cash_pledge
            ];
            OrderGoods::where(['order_id' => $orderId])->update($update);
            OrderLog::addOrderLog($orderId, $this->users['id'], OrderLog::ORDER_LOG_OPERATE_TYPE_ADMIN, '设置付款押金' . $cash_pledge);
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        } catch (\Exception $exception) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
        }
    }


    /**
     * 订单征信-个人征信授权书-查询订单创建-新征信接口
     */
    public function getCreditData(Request $request){
        $input = $request->input();
        return ReturnMsg(CommonService::HTTP_CODE_FAIL,'不支持查看征信');

        if(!empty($input['orderId'])){
            $order = Order::from('sp_order_2 as o')->where('o.id',$input['orderId'])
                ->leftjoin('sp_member_2 as m','m.id','o.uid')
                ->select(
                    'o.id','o.uid','o.mobile as user_mobile','o.pact_url_2','o.trade_no'
                    ,'m.cert_name','m.cert_no','o.pact_url_3','m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
                )
                ->first();
            $order = $order ? $order->toArray() : [];

            if(empty($order['idcard_front'])||empty($order['idcard_back'])){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请上传身份证');
            }

            //添加备注
            $add = [
                'uid'=>$this->users['id'],
                'username'=>$this->users['username'],
                'create_time'=>time(),
                'remark'=>$this->users['username'].'查看征信',
                'order_id'=>$input['orderId']
            ];
            OrderRemark::insert($add);

            $risk_data = OrderCredit::getCreditData($input['orderId']);

            //有则输出，无则添加
            if($risk_data){
                if($risk_data['result2']){
                    $code = json_decode($risk_data['result2'],true);
                    if($code['code'] == 'ZHZ0000'){
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'正在查询征信，请稍等片刻再点击按钮');
                    }else{
                        if(empty($order['pact_url_2'])||empty($order['pact_url_3'])){
                            //未签署个人征信授权书
                            $countResOne=OrderCredit::where('order_id',$order['id'])->lockForUpdate()->first();
                            if(!$countResOne){
                                $risk_data=['code'=>'0','message'=>'查询中'];
                                OrderCredit::setRiskData($input['orderId'],$risk_data,$order['cert_name'],$order['mobile'],$order['cert_no']);
                                OrderService::createTwo($order);
                                OrderService::createTwoOne($order);
                                Order::where('id',$order['id'])->update(['is_credit_select'=>'2']);
                            }
                        }else{
                            $countRes=OrderCredit::where('order_id',$order['id'])->orderby('id','desc')->value('scoreNo');
                            if($order['pact_url_2']&&!$countRes){
                                $order = Order::from('sp_order_2 as o')->where('o.id',$order['id'])
                                    ->leftjoin('sp_member_2 as m','m.id','o.uid')
                                    ->select(
                                        'o.id','o.uid','o.mobile as user_mobile','o.pact_url_2','o.trade_no'
                                        ,'m.cert_name','m.cert_no','o.pact_url_3','m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
                                    )
                                    ->first();
                                $order = $order ? $order->toArray() : [];

                                $risk_data = CreditCallService::getInvestData($order);

                                OrderCredit::setRiskData($order['id'],$risk_data,$order['cert_name'],$order['mobile'],$order['cert_no']);
                                Order::where('id',$order['id'])->update(['is_credit_select'=>'2']);
                            }
                        }
                        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'',['msg'=>'查询中']);
                    }
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'征信查询有误，请联系客服处理');
                }
            }else{

                if(empty($order['pact_url_2'])||empty($order['pact_url_3'])){
                    //未签署个人征信授权书
                    $countResOne=OrderCredit::where('order_id',$order['id'])->lockForUpdate()->first();
                    if(!$countResOne){
                        $risk_data=['code'=>'0','message'=>'查询中'];
                        OrderCredit::setRiskData($input['orderId'],$risk_data,$order['cert_name'],$order['mobile'],$order['cert_no']);
                        OrderService::createTwo($order);
                        OrderService::createTwoOne($order);
                        Order::where('id',$order['id'])->update(['is_credit_select'=>'2']);
                    }
                }else{
                    $countRes=OrderCredit::where('order_id',$order['id'])->orderby('id','desc')->value('scoreNo');
                    if($order['pact_url_2']&&!$countRes){
                        $order = Order::from('sp_order_2 as o')->where('o.id',$order['id'])
                            ->leftjoin('sp_member_2 as m','m.id','o.uid')
                            ->select(
                                'o.id','o.uid','o.mobile as user_mobile','o.pact_url_2','o.trade_no'
                                ,'m.cert_name','m.cert_no','o.pact_url_3','m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
                            )
                            ->first();
                        $order = $order ? $order->toArray() : [];

                        $risk_data = CreditCallService::getInvestData($order);

                        OrderCredit::setRiskData($order['id'],$risk_data,$order['cert_name'],$order['mobile'],$order['cert_no']);
                        Order::where('id',$order['id'])->update(['is_credit_select'=>'2']);
                    }
                }

                $order = Order::from('sp_order_2 as o')->where('o.id',$input['orderId'])
                    ->leftjoin('sp_member_2 as m','m.id','o.uid')
                    ->select(
                        'o.id','o.uid','o.mobile as user_mobile','o.pact_url_2','o.trade_no'
                        ,'m.cert_name','m.cert_no','o.pact_url_3','m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
                    )
                    ->first();
                $order = $order ? $order->toArray() : [];

                $online_data['user_type'] = OrderService::RISK_USER_TYPE_ADMIN; //管理员查看
                $online_data['username'] = $this->users['username']; //查看人员

                OrderCredit::editCreditData($input['orderId'],$online_data);

            }

            // $res = obToArray($risk_data);

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'请求成功',['msg'=>'请求成功,稍后点击查看']);

        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请选择要查询征信报告的订单');
        }
    }
    /**
     * 订单征信-个人征信授权书-查询订单创建-新征信接口
     */
    public function getCreditData2(Request $request){
        $input = $request->input();
        if(!empty($input['orderId'])){
            //查询
            //查询
            $order = Order::from('sp_order_2 as o')->where('o.id',$input['orderId'])
                ->leftjoin('sp_member_2 as m','m.id','o.uid')
                ->select(
                    'o.id','o.uid','o.mobile as user_mobile','o.pact_url_2','o.trade_no'
                    ,'m.cert_name','m.cert_no'
                    ,'m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
                )
                ->first();
            $order = $order ? $order->toArray() : [];
            $risk_data=OrderCredit::where('cert_no',$order['cert_no'])->where('result','!=','')->where('start_at','>',date('Y-m-d H:i:s',strtotime('-7 day')))->orderby('id','desc')->first();
            $risk_data = $risk_data ? $risk_data->toArray() : array();
            if(!$risk_data){
                $risk_data=OrderCredit::getCreditData($order['id']);
            }


            // $risk_data = OrderCredit::getCreditData($input['orderId']);
            $risk_data_res=$risk_data;
            $risk_data2 = json_decode($risk_data['result2'],true);
            //有数据
            if($risk_data){
                $result = json_decode($risk_data['result2'],true);

                if($result){//有征信结果，输出
                    if(!isset($result['code'])){
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL,'没有查到征信');
                    }
                    $code1 =$result['code'];
                    // dd($code1);

                    if($code1 != 'ZHZ0000'){
                        $countRes=OrderCredit::where('order_id',$input['orderId'])->orderby('id','desc')->value('scoreNo');
                        if($order['pact_url_2']&&!$countRes){
                            $order = Order::from('sp_order_2 as o')->where('o.id',$order['id'])
                                ->leftjoin('sp_member_2 as m','m.id','o.uid')
                                ->select(
                                    'o.id','o.uid','o.mobile as user_mobile','o.pact_url_2','o.trade_no'
                                    ,'m.cert_name','m.cert_no','o.pact_url_3','m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
                                )
                                ->first();
                            $order = $order ? $order->toArray() : [];

                            $risk_data = CreditCallService::getInvestData($order);

                            OrderCredit::setRiskData($order['id'],$risk_data,$order['cert_name'],$order['mobile'],$order['cert_no']);
                        }
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL,$result['message']);
                    }else{
                        $resa= json_decode($risk_data['result'],true);

                        if($resa['code'] == 'ZHZ0000' ){
                            $risk_data['cert_name'] = $risk_data_res['cert_name'];

                            $risk_data['mobile'] = $risk_data_res['mobile'];

                            $risk_data['cert_no'] = $risk_data_res['cert_no'];
                            $risk_data['data'] = json_decode($risk_data['result'])->data;
                        }else if(!isset($resa['code']) ){
                            $risk_data = CreditCallService::getInvestData2($risk_data['requestId'],$risk_data['scoreNo']);
                            $online_data['result'] = json_encode($risk_data);

                            $risk_data['cert_name'] = $risk_data_res['cert_name'];

                            $risk_data['mobile'] = $risk_data_res['mobile'];

                            $risk_data['cert_no'] = $risk_data_res['cert_no'];

                            $risk_data['order_id'] = $input['orderId'];


                            $risk_data['start_at'] = date('Y-m-d H:i:s',time());

                            $risk_data['end_at'] =  date('Y-m-d H:i:s',time()+7*24*60*60);

                            $online_data['result'] = json_encode($risk_data);

                            OrderCredit::editCreditData($input['orderId'],$online_data);
                            if($risk_data['code'] != 'ZHZ0000'){
                                return ReturnMsg(CommonService::HTTP_CODE_FAIL,$risk_data['message']);
                            }
                            $risk_data['result']=$online_data['result'];
                        }else if(isset($resa['code']) ){
                            $risk_data = CreditCallService::getInvestData2($risk_data['requestId'],$risk_data['scoreNo']);
                            $online_data['result'] = json_encode($risk_data);


                            $risk_data['cert_name'] = $risk_data_res['cert_name'];

                            $risk_data['mobile'] = $risk_data_res['mobile'];

                            $risk_data['cert_no'] = $risk_data_res['cert_no'];

                            $risk_data['order_id'] = $input['orderId'];


                            $risk_data['start_at'] = date('Y-m-d H:i:s',time());

                            $risk_data['end_at'] =  date('Y-m-d H:i:s',time()+7*24*60*60);

                            $online_data['result'] = json_encode($risk_data);

                            OrderCredit::editCreditData($input['orderId'],$online_data);
                            if($risk_data['code'] != 'ZHZ0000'){
                                return ReturnMsg(CommonService::HTTP_CODE_FAIL,$risk_data['message']);
                            }
                            $risk_data['result']=$online_data['result'];
                        }

                        //结果已出来
                        $risk_data_res['data'] = json_decode($risk_data['result'],true)['data'];
                    }
                }
                $res = obToArray($risk_data);
                if(!$res['data']){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,$res['data']['result']['message']);
                }

                $jsonString = str_replace("'", '"', $res['data']['result']['modelResult']);
                $res['data']['result']['modelResult'] = json_decode($jsonString, true);
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'请求成功',$res);

            }else{ //没有数据
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请查询后再获取');
            }

        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请选择要查询征信报告的订单');
        }
    }

    /**
     * 订单征信-上征信-签署用户授权协议
     */
    public function setCreditData(Request $request)
    {
        $input = $request->input();

        if (!empty($input['orderId'])) {
            //订单征信-上征信-签署用户授权协议
            $order = Order::from('sp_order_2 as o')->where('o.id', $input['orderId'])
                ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
                ->select(
                    'o.id', 'o.uid', 'o.mobile as user_mobile', 'o.pact_url_2', 'o.pact_url_3'
                    , 'm.cert_name', 'm.cert_no', 'm.mobile', 'm.esign_user_id', 'm.esign_seal_id', 'm.user_id', 'm.idcard_front', 'm.idcard_back'
                )
                ->first();
            $order = $order ? $order->toArray() : [];
            if (empty($order['pact_url_3'])) {
                $res = OrderService::createOne($order);
                if ($res) {
                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已上征信，请勿重复操作');
            }


        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要上征信报告的订单');
        }
    }

    /**
     * 订单征信-上征信-申请担保
     */
    public function setCreditData2(Request $request)
    {
        $input = $request->input();

        if (!empty($input['orderId'])) {
            //订单征信-上征信-签署用户授权协议
            $order = Order::from('sp_order_2 as o')->where('o.id', $input['orderId'])
                ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
                ->select(
                    'o.id', 'o.pact_url_2', 'o.pact_url_3', 'o.is_credit_up', 'o.address', 'o.trade_no', 'o.rent_total', 'o.month_total', 'o.begin_time', 'o.end_time', 'o.city'
                    , 'm.cert_name', 'm.cert_no', 'm.mobile', 'm.idcard_front', 'm.idcard_back', 'm.gender'
                )
                ->first();
            $order = $order ? $order->toArray() : [];
            if ($order['is_credit_up'] == '1') {

                $order['rid'] = Areas::where('name', $order['city'])->value('rid');

                $res = CreditService::applyInvestData($order, $input);
                if ($res['code'] == '0') {

                    Order::where('id', $input['orderId'])->update(['is_credit_up' => 2]);

                    //更新订单征信数据
                    $online_data = [];
                    $online_data['platformLoanNo'] = $res['data']['platformLoanNo'];
                    $online_data['loanNo'] = $order['trade_no'];
                    $online_data['is_set'] = '1';

                    OrderCredit::editCreditData($input['orderId'], $online_data);

                    return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '操作成功');
                } else {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '操作失败');
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '已上征信，请勿重复操作');
            }

        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请选择要上征信报告的订单');
        }
    }


    /**
     * 新颜雷达
     * @param Request $request
     * @return false|string
     */
    public function getXinyanRadarData(Request $request)
    {
        $input = $request->input();

        if(!empty($input['orderId'])){

            $risk_data = OrderRadarXinyan::getRiskData($input['orderId']);

            //有则输出，无则添加
            if($risk_data){

                $risk_data['data'] = json_decode($risk_data['result'])->data;

                $risk_data['risk_probe']=json_decode($risk_data['risk_probe_result']);

                // $risk_data['result2'] = json_decode($risk_data['result2']);

            }else{
                //全景雷达
                $risk_data = XinyanService::fxTan($input);

                OrderRadarXinyan::setRiskData($input['orderId'],$risk_data,$input['cert_name'],$input['mobile'],$input['cert_no']);

                $risk_data['cert_name'] = $input['cert_name'];

                $risk_data['mobile'] = $input['mobile'];

                $risk_data['cert_no'] = $input['cert_no'];

                $risk_data['order_id'] = $input['orderId'];


                $risk_data['start_at'] = date('Y-m-d H:i:s');

                $risk_data['end_at'] =  date('Y-m-d H:i:s',time()+7*24*60*60);



                $online_data = [];

                $online_data['user_type'] = OrderService::RISK_USER_TYPE_ADMIN; //管理员查看

                OrderRadarXinyan::editRiskData($input['orderId'],$online_data);

//                $resRiskProbe=XinyanService::fxTan($input);
//                OrderRadarXinyan::editRiskProbeData($input['orderId'],$resRiskProbe);
//                $risk_data['risk_probe']=json_decode($resRiskProbe,true);
            }

            $res = obToArray($risk_data);


            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$res);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请选择要风控的订单');
        }
    }

    /**
     * 流水账单报告
     * @param Request $request
     */
    public function billReport(Request $request)
    {
        $order = Order::from('sp_order_2 as o')->where('o.id', $request['order_id'])
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->select(
                'o.id', 'o.uid', 'm.mobile', 'o.trade_no', 'o.seller_id'
                , 'm.cert_name', 'm.cert_no', 'm.user_id'
                , 'm.education', 'o.status', 'm.level'
            )
            ->first();
        if (empty($order)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
        $res = BillReport::query($order['cert_name'], $order['cert_no'], $order['mobile']);
        if ($res) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功', $res);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '流水报告获取失败');
        }


    }

    /**
     * 退款手续费修改
     * @param Request $request
     * @return false|string
     */
    public function updateOrderTransactionFee(Request $request)
    {
        if (empty($request['order_id'])) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '请选择订单');
        }
        if (empty($request['transaction_fee'])||!is_numeric($request['transaction_fee'])||$request['transaction_fee']<=0) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '请选择交易手续费，必须大于0');
        }

        $res = OrderGoods::query()->where('order_id', $request['order_id'])->update(['transaction_fee' => $request['transaction_fee']]);
        if ($res) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功');
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
        }
    }

}
